package com.api.workflow.web;

import com.api.workflow.util.YNHttpUtils;
import com.weaver.general.BaseBean;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.TimeUtil;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.*;

/*
 * 接口11   OA获取SAP内部订单(无订单预付)
 * */
public class YNFII009Task extends BaseCronJob {
    @Override
    public void execute() {

        BaseBean baseBean = new BaseBean();

        try {

            RecordSet rs = new RecordSet();

            String sql = "select gsdm from uf_gsdykzfwb";
            boolean b0 = rs.execute(sql);
            baseBean.writeLog("wyq==FII009=========sql" + sql+"===="+b0);

            List<String> gsdm = new ArrayList<>();
            while (rs.next()) {
                gsdm.add(rs.getString("gsdm"));
            }

            String sql1 = "select bm from uf_XMLXB";
            boolean b = rs.execute(sql1);
            baseBean.writeLog("wyq==FII009=========sql1" + sql1+"===="+b);

            while (rs.next()) {
                String bm = rs.getString("bm");
                for (String s : gsdm) {
                    JSONObject jsonObject = new JSONObject();

                    jsonObject.put("BUKRS", s);
                    jsonObject.put("AUART", bm);
                    baseBean.writeLog("wyq==FII009=========jsonObject" + jsonObject.toString());
                    String post = YNHttpUtils.FII009(jsonObject.toString(), YNHttpUtils.token());

                    baseBean.writeLog("wyq==FII009=========post" + post);
                    JSONObject jsonPOST = JSONObject.parseObject(post);

                    String STATUS = jsonPOST.getString("STATUS");
                    String MESSAGE = jsonPOST.getString("MESSAGE");
                    if ("S".equals(STATUS)) {

                        RecordSet rs1 = new RecordSet();
                        JSONArray data = jsonPOST.getJSONArray("DATA");
                        for (int i = 0; i < data.size(); i++) {
                            JSONObject jsonObject1 = data.getJSONObject(i);
                            //查询数据库是否已存在
                            String select = "select * from uf_nbddbd where ddbh = '" + jsonObject1.getString("AUFNR")+ "'";

                            baseBean.writeLog("wyq==FII009=========select" + select);

                            boolean b1 = rs1.execute(select);
                            baseBean.writeLog("wyq==FII009=========b1" + b1);

                            Map<String, Object> objectObjectHashMap = new HashMap<>();
                            objectObjectHashMap.put("ddbh",jsonObject1.get("AUFNR"));
                            objectObjectHashMap.put("ms",jsonObject1.get("KTEXT"));
                            objectObjectHashMap.put("ddlx",jsonObject1.get("AUART"));
                            objectObjectHashMap.put("dwb",jsonObject1.get("TXT"));
                            objectObjectHashMap.put("gsdm",jsonObject1.get("BUKRS"));
                            objectObjectHashMap.put("fzdcbzx",jsonObject1.get("KOSTV"));
                            objectObjectHashMap.put("lrzx",jsonObject1.get("PRCTR"));
                            objectObjectHashMap.put("ysje",jsonObject1.get("WLGES"));

                            Map<String, Object> whereMap = new HashMap<>();
                            rs1.next();
                            int counts = rs1.getCounts();
                            if(counts == 0){
                                //插入数据库
                                int modeId = getModeId("uf_nbddbd");
                                boolean b2 = insetModeData("uf_nbddbd", objectObjectHashMap, 1, modeId);
                                baseBean.writeLog("wyq==FII009=========新增" + b2);
                            }else {
                                //更新数据库
                                whereMap.put("ddbh", objectObjectHashMap.get("ddbh"));
                                boolean b2 = updateModeData1("uf_nbddbd", objectObjectHashMap, whereMap);
                                baseBean.writeLog("wyq==FII009=========更新" + b2);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            baseBean.writeLog("wyq==FII009=========Exception" + e.toString());
        }
    }
    /**
     * 插入到建模表数据
     *
     * @param tableName
     * @param data
     * @param hrmResourceId
     * @param modeId
     * @return
     * @throws Exception
     */
    public static boolean insetModeData(String tableName, Map<String, Object> data, int hrmResourceId, int modeId) throws Exception {
        List<Object> dataList = new ArrayList<>();
        String columns = "";
        String values = "";
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            columns += (key + ",");
            values += ("?,");
            dataList.add(value);
        }

        String insertSql = "insert into  " + tableName + "(" +
                columns +
                " formmodeid," +
                " modedatacreater," +
                " modedatacreatertype," +
                " modedatacreatedate," +
                " modedatacreatetime, " +
                " MODEUUID" +
                ") values(" +
                values +
                "?,?,?,?,?,?)";
        String currentDateString = TimeUtil.getCurrentDateString();
        String currentTimeString = TimeUtil.getOnlyCurrentTimeString();
        String uuid = UUID.randomUUID().toString();

        Object[] objects = new Object[]{
                modeId, hrmResourceId, 0, currentDateString, currentTimeString, uuid
        };
        dataList.addAll(Arrays.asList(objects));

        RecordSet insertRs = new RecordSet();
        boolean b1 = insertRs.executeUpdate(insertSql, dataList.toArray());
        if (b1) {
            RecordSet recordSet1 = new RecordSet();
            recordSet1.executeQuery("select max(id) as billid from " + tableName + " ");
            if (recordSet1.next()) {
                int billid = recordSet1.getInt("billid");
                ModeRightInfo ModeRightInfo = new ModeRightInfo();
                ModeRightInfo.setNewRight(true);
                ModeRightInfo.editModeDataShare(1, modeId, billid);
            }
        }
        return b1;
    }

    /**
     * @param tablename
     * @return
     */
    public static int getModeId(String tablename) {
        RecordSet rs = new RecordSet();
        Map<String, Integer> map = new HashMap<>();
        rs.executeQuery("select b.tablename,a.formid,b.detailkeyfield,a.id from modeinfo a,workflow_bill b where a.formid = b.id  and tablename=?", tablename);
        if (rs.next()) {
            int id = rs.getInt("id");
            return id;
        }
        return 0;
    }

    public static boolean updateModeData1 (String tableName, Map<String, Object> data, Map<String, Object> updateData){
        StringBuilder updateSql = new StringBuilder("update  " + tableName + " set ");
        ArrayList<Object> objects = new ArrayList<>();
        // 处理 SET 部分
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();

            updateSql.append(key).append(" = ?,");
            objects.add(value);
        }
        if (updateSql.length() > 0 && String.valueOf(updateSql).endsWith(",")) {
            updateSql.deleteCharAt(updateSql.length() - 1);
        }
        updateSql.append(" where 1=1 ");
        if (updateData != null && !updateData.isEmpty()) {
            for (Map.Entry<String, Object> stringObjectEntry : updateData.entrySet()) {
                String key = stringObjectEntry.getKey();
                Object value = stringObjectEntry.getValue();

                updateSql.append("and ").append(key).append(" = ?,");
                objects.add(value);
            }
        }
        if (updateSql.length() > 0 && String.valueOf(updateSql).endsWith(",")) {
            updateSql.deleteCharAt(updateSql.length() - 1);
        }
        RecordSet recordSet = new RecordSet();
        return recordSet.executeUpdate(updateSql.toString(), objects.toArray());
    }

    public static boolean updateModeData(String tableName, Map<String, Object> data, Map<String, Object> updateData) throws Exception {
        String columns = "";
        String updateColumns = "";
        // 处理 SET 部分
        for (Map.Entry<String, Object> stringObjectEntry : data.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null) {
                columns += key + " = NULL, ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    columns += key + " = '', ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    columns += key + " = '" + escaped + "', ";
                }
            } else {
                columns += key + " = " + value + ", ";
            }
        }

        // 处理 WHERE 条件
        for (Map.Entry<String, Object> stringObjectEntry : updateData.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value == null) {
                updateColumns += key + " = NULL AND ";
            } else if (value instanceof String) {
                String strValue = (String) value;
                if (strValue.isEmpty()) {
                    updateColumns += key + " = '' AND ";
                } else {
                    String escaped = strValue.replace("'", "''");
                    updateColumns += key + " = '" + escaped + "' AND ";
                }
            } else {
                updateColumns += key + " = " + value + " AND ";
            }
        }

        String insertSql = "update  " + tableName + " set " + columns;
        if (insertSql.endsWith(", ")) {
            insertSql = insertSql.substring(0, insertSql.length() - 2);
        }
        insertSql = insertSql + " where ";
        if (updateColumns.endsWith("AND ")) {
            updateColumns = updateColumns.substring(0, updateColumns.length() - 4);
        }
        insertSql = insertSql + updateColumns;
        RecordSet updateRs = new RecordSet();
        return updateRs.executeUpdate(insertSql);
    }


}
